use crate::browser::BrowserManager;
use crate::database::{Account, Database};
use anyhow::{anyhow, Result};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;
use uuid::Uuid;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct XiaohongshuAccount {
    pub id: String,
    pub username: String,
    pub nickname: String,
    pub phone: String,
    pub status: String,
    pub followers: i32,
    pub following: i32,
    pub posts: i32,
    pub last_login: String,
    pub cookies: Option<String>,
    pub token: Option<String>,
    pub is_current: bool,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct LoginResult {
    pub success: bool,
    pub message: String,
    pub account: Option<XiaohongshuAccount>,
    pub cookies: Option<String>,
    pub token: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SyncResult {
    pub success: bool,
    pub message: String,
    pub data: Option<AccountData>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountData {
    pub followers: i32,
    pub following: i32,
    pub posts: i32,
    pub last_login: String,
}

pub struct XiaohongshuService {
    pub browser_manager: Arc<Mutex<BrowserManager>>,
    pub database: Arc<Mutex<Database>>,
}

impl XiaohongshuService {
    pub fn new() -> Result<Self> {
        Ok(Self {
            browser_manager: Arc::new(Mutex::new(BrowserManager::new()?)),
            database: Arc::new(Mutex::new(Database::new()?)),
        })
    }

    pub async fn open_login_page(&self) -> Result<()> {
        println!("打开小红书登录页面...");
        
        let mut browser_manager = self.browser_manager.lock().await;
        
        // 确保浏览器已初始化
        if !browser_manager.is_initialized() {
            browser_manager.initialize().await?;
        }
        
        // 打开登录页面
        browser_manager.open_login_page().await?;
        
        println!("登录页面已打开，请手动完成登录");
        Ok(())
    }

    pub async fn check_status(&self) -> Result<bool> {
        println!("开始检查登录状态...");
        
        let browser_manager = self.browser_manager.lock().await;
        
        if !browser_manager.is_initialized() {
            println!("浏览器未初始化，返回false");
            return Ok(false);
        }
        
        println!("调用浏览器管理器检查登录状态...");
        let result = browser_manager.check_login_status().await;
        println!("浏览器管理器返回结果: {:?}", result);
        
        result
    }

    pub async fn get_login_info_and_save(&self) -> Result<LoginResult> {
        println!("获取登录信息并保存...");
        
        let browser_manager = self.browser_manager.lock().await;
        let database = self.database.lock().await;
        
        // 检查登录状态
        let is_logged_in = browser_manager.check_login_status().await?;
        
        if !is_logged_in {
            return Ok(LoginResult {
                success: false,
                message: "用户未登录，请先完成登录".to_string(),
                account: None,
                cookies: None,
                token: None,
            });
        }
        
        // 获取登录信息
        let login_info_json = browser_manager.get_login_info().await?;
        let login_info: serde_json::Value = serde_json::from_str(&login_info_json)?;
        
        // 解析cookies
        let cookies = if let Some(cookies_array) = login_info.get("cookies") {
            serde_json::to_string(cookies_array)?
        } else {
            "[]".to_string()
        };
        
        // 生成token
        let token = format!("token_{}", Uuid::new_v4());
        
        // 获取用户信息
        let user_info = login_info.get("userInfo")
            .and_then(|v| v.as_str())
            .unwrap_or("未知用户");
        
        // 获取页面标题作为手机号标识（临时方案）
        let title = login_info.get("title")
            .and_then(|v| v.as_str())
            .unwrap_or("未知");
        
        // 生成一个临时的手机号标识
        let phone = format!("user_{}", Uuid::new_v4().to_string().split('-').next().unwrap_or("unknown"));
        
        // 检查账号是否已存在（这里简化处理，实际应该从登录信息中获取真实手机号）
        let existing_account = database.get_account_by_phone(&phone)?;
        
        let account_id = if let Some(existing) = existing_account {
            // 更新现有账号
            let existing_id = existing.id.clone();
            let updated_account = Account {
                id: existing_id.clone(),
                username: user_info.to_string(),
                nickname: format!("用户_{}", phone),
                phone: phone.clone(),
                status: "active".to_string(),
                followers: 0,
                following: 0,
                posts: 0,
                last_login: Some(Utc::now().to_rfc3339()),
                cookies: Some(cookies.clone()),
                token: Some(token.clone()),
                is_current: true,
                created_at: existing.created_at,
                updated_at: Utc::now().to_rfc3339(),
            };
            
            database.update_account(&existing_id, &updated_account)?;
            existing_id
        } else {
            // 创建新账号
            let new_account = Account {
                id: Uuid::new_v4().to_string(),
                username: user_info.to_string(),
                nickname: format!("用户_{}", phone),
                phone: phone.clone(),
                status: "active".to_string(),
                followers: 0,
                following: 0,
                posts: 0,
                last_login: Some(Utc::now().to_rfc3339()),
                cookies: Some(cookies.clone()),
                token: Some(token.clone()),
                is_current: true,
                created_at: Utc::now().to_rfc3339(),
                updated_at: Utc::now().to_rfc3339(),
            };
            
            let new_id = new_account.id.clone();
            database.add_account(&new_account)?;
            new_id
        };
        
        // 将其他账号设为非当前账号
        database.set_all_accounts_not_current()?;
        
        // 设置当前账号
        database.set_current_account(&account_id)?;
        
        // 构建返回的账号信息
        let account = XiaohongshuAccount {
            id: account_id,
            username: user_info.to_string(),
            nickname: format!("用户_{}", phone),
            phone: phone,
            status: "active".to_string(),
            followers: 0,
            following: 0,
            posts: 0,
            last_login: Utc::now().to_rfc3339(),
            cookies: Some(cookies.clone()),
            token: Some(token.clone()),
            is_current: true,
            created_at: Utc::now().to_rfc3339(),
            updated_at: Utc::now().to_rfc3339(),
        };
        
        println!("登录信息获取并保存成功");
        
        Ok(LoginResult {
            success: true,
            message: "登录信息获取并保存成功".to_string(),
            account: Some(account),
            cookies: Some(cookies),
            token: Some(token),
        })
    }

    pub async fn sync_data(&self, account_id: &str) -> Result<SyncResult> {
        println!("开始同步账号数据...");
        
        let database = self.database.lock().await;
        
        // 获取账号信息
        let account = database.get_account(account_id)?;
        if account.is_none() {
            return Ok(SyncResult {
                success: false,
                message: "账号不存在".to_string(),
                data: None,
            });
        }
        
        // 模拟同步数据（实际应该从小红书API获取）
        let data = AccountData {
            followers: 1250,
            following: 89,
            posts: 45,
            last_login: Utc::now().to_rfc3339(),
        };
        
        println!("数据同步完成");
        
        Ok(SyncResult {
            success: true,
            message: "同步成功".to_string(),
            data: Some(data),
        })
    }

    pub async fn switch_account(&self, account_id: &str) -> Result<()> {
        println!("切换账号: {}", account_id);
        
        let database = self.database.lock().await;
        
        // 将所有账号设为非当前
        database.set_all_accounts_not_current()?;
        
        // 设置指定账号为当前账号
        database.set_current_account(account_id)?;
        
        println!("账号切换成功");
        Ok(())
    }

    pub async fn get_current_account(&self) -> Result<Option<XiaohongshuAccount>> {
        let database = self.database.lock().await;
        let account = database.get_current_account()?;
        
        if let Some(acc) = account {
            let xhs_account = XiaohongshuAccount {
                id: acc.id,
                username: acc.username,
                nickname: acc.nickname,
                phone: acc.phone,
                status: acc.status,
                followers: acc.followers,
                following: acc.following,
                posts: acc.posts,
                last_login: acc.last_login.unwrap_or_default(),
                cookies: acc.cookies,
                token: acc.token,
                is_current: acc.is_current,
                created_at: acc.created_at,
                updated_at: acc.updated_at,
            };
            Ok(Some(xhs_account))
        } else {
            Ok(None)
        }
    }

    pub async fn publish(&self, _title: &str, _content: &str, _images: Option<Vec<String>>) -> Result<()> {
        println!("开始发布文章...");
        
        let browser_manager = self.browser_manager.lock().await;
        
        // 确保浏览器已初始化
        if !browser_manager.is_initialized() {
            return Err(anyhow!("浏览器未初始化"));
        }
        
        // 检查登录状态
        let is_logged_in = browser_manager.check_login_status().await?;
        if !is_logged_in {
            return Err(anyhow!("用户未登录，请先登录"));
        }
        
        // 这里应该实现真实的发布逻辑
        // 暂时返回成功
        println!("文章发布成功");
        Ok(())
    }
} 